<template>
  <div class="ai-chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-left">
        <el-avatar :size="40" src="/ai-avatar.png" />
        <div class="ai-info">
          <h3>智能助手</h3>
          <p>{{ currentModel.name || 'GPT-3.5' }}</p>
        </div>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleModelChange">
          <el-button type="text">
            切换模型<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item 
                v-for="model in availableModels"
                :key="model.id"
                :command="model.id"
              >
                {{ model.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="clearChat" type="text" icon="Delete">清空对话</el-button>
        <el-button @click="showHistory = true" type="text" icon="Clock">历史记录</el-button>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="message in messages"
        :key="message.id"
        class="message-item"
        :class="{ 'user-message': message.role === 'user', 'ai-message': message.role === 'assistant' }"
      >
        <div class="message-avatar">
          <el-avatar 
            :size="32" 
            :src="message.role === 'user' ? userAvatar : '/ai-avatar.png'"
          />
        </div>
        <div class="message-content">
          <div class="message-header">
            <span class="message-role">{{ message.role === 'user' ? '我' : 'AI助手' }}</span>
            <span class="message-time">{{ formatTime(message.createTime) }}</span>
          </div>
          <div class="message-text" v-html="formatMessage(message.content)"></div>
          <div class="message-actions" v-if="message.role === 'assistant'">
            <el-button size="small" type="text" @click="copyMessage(message.content)">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
            <el-button size="small" type="text" @click="regenerateMessage(message)">
              <el-icon><Refresh /></el-icon>
              重新生成
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- AI正在输入 -->
      <div v-if="isTyping" class="message-item ai-message">
        <div class="message-avatar">
          <el-avatar :size="32" src="/ai-avatar.png" />
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-tools">
        <el-button size="small" type="text" @click="showTemplates = true">
          <el-icon><Document /></el-icon>
          模板
        </el-button>
        <el-upload
          :show-file-list="false"
          :before-upload="handleFileUpload"
          accept="image/*,.pdf,.doc,.docx,.txt"
        >
          <el-button size="small" type="text">
            <el-icon><Paperclip /></el-icon>
            附件
          </el-button>
        </el-upload>
        <el-button size="small" type="text" @click="toggleVoiceInput">
          <el-icon><Microphone /></el-icon>
          语音
        </el-button>
      </div>
      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="输入您的问题..."
          @keydown.enter.exact="handleSend"
          @keydown.enter.shift.exact.prevent="inputMessage += '\n'"
          :disabled="isTyping"
        />
        <el-button 
          type="primary" 
          @click="handleSend"
          :loading="isTyping"
          :disabled="!inputMessage.trim()"
          class="send-button"
        >
          发送
        </el-button>
      </div>
    </div>

    <!-- 聊天模板对话框 -->
    <el-dialog v-model="showTemplates" title="聊天模板" width="600px">
      <div class="template-list">
        <div 
          v-for="template in chatTemplates"
          :key="template.id"
          class="template-item"
          @click="useTemplate(template)"
        >
          <h4>{{ template.title }}</h4>
          <p>{{ template.description }}</p>
        </div>
      </div>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog v-model="showHistory" title="聊天历史" width="800px">
      <div class="history-list">
        <div 
          v-for="session in chatSessions"
          :key="session.id"
          class="history-item"
          @click="loadSession(session)"
        >
          <div class="session-info">
            <h4>{{ session.title || '未命名对话' }}</h4>
            <p>{{ formatTime(session.createTime) }}</p>
          </div>
          <div class="session-actions">
            <el-button size="small" type="text" @click.stop="deleteSession(session)">
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  sendAiMessage,
  getChatHistory,
  createChatSession,
  getChatSessions,
  deleteChatSession,
  clearChatHistory,
  getAvailableModels,
  getChatTemplates,
  uploadChatFile
} from '@/api/aiChat'

const userStore = useUserStore()

// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const isTyping = ref(false)
const currentSessionId = ref(null)
const currentModel = ref({ id: 'gpt35', name: 'GPT-3.5' })
const availableModels = ref([])
const chatTemplates = ref([])
const chatSessions = ref([])
const showTemplates = ref(false)
const showHistory = ref(false)
const messagesContainer = ref()

// 计算属性
const userAvatar = computed(() => userStore.userInfo?.avatar || '/default-avatar.png')

// 获取可用模型
const loadAvailableModels = async () => {
  try {
    const response = await getAvailableModels()
    if (response.code === 200) {
      availableModels.value = response.data
    }
  } catch (error) {
    console.error('获取模型列表失败:', error)
  }
}

// 获取聊天模板
const loadChatTemplates = async () => {
  try {
    const response = await getChatTemplates()
    if (response.code === 200) {
      chatTemplates.value = response.data
    }
  } catch (error) {
    console.error('获取聊天模板失败:', error)
  }
}

// 获取聊天会话
const loadChatSessions = async () => {
  try {
    const response = await getChatSessions()
    if (response.code === 200) {
      chatSessions.value = response.data
    }
  } catch (error) {
    console.error('获取聊天会话失败:', error)
  }
}

// 创建新会话
const createNewSession = async () => {
  try {
    const response = await createChatSession({
      modelId: currentModel.value.id,
      title: '新对话'
    })
    if (response.code === 200) {
      currentSessionId.value = response.data.id
      return response.data.id
    }
  } catch (error) {
    console.error('创建会话失败:', error)
  }
  return null
}

// 发送消息
const handleSend = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return

  const userMessage = {
    id: Date.now(),
    role: 'user',
    content: inputMessage.value,
    createTime: new Date()
  }

  messages.value.push(userMessage)
  const messageContent = inputMessage.value
  inputMessage.value = ''
  isTyping.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 如果没有会话ID，创建新会话
    if (!currentSessionId.value) {
      currentSessionId.value = await createNewSession()
    }

    const response = await sendAiMessage({
      sessionId: currentSessionId.value,
      message: messageContent,
      modelId: currentModel.value.id
    })

    if (response.code === 200) {
      const aiMessage = {
        id: Date.now() + 1,
        role: 'assistant',
        content: response.data.content,
        createTime: new Date()
      }
      messages.value.push(aiMessage)
    } else {
      ElMessage.error(response.message || 'AI回复失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  } finally {
    isTyping.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 切换模型
const handleModelChange = (modelId) => {
  const model = availableModels.value.find(m => m.id === modelId)
  if (model) {
    currentModel.value = model
    ElMessage.success(`已切换到 ${model.name}`)
  }
}

// 清空对话
const clearChat = async () => {
  try {
    await ElMessageBox.confirm('确认要清空当前对话吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (currentSessionId.value) {
      await clearChatHistory(currentSessionId.value)
    }
    
    messages.value = []
    currentSessionId.value = null
    ElMessage.success('对话已清空')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空对话失败:', error)
      ElMessage.error('清空对话失败')
    }
  }
}

// 使用模板
const useTemplate = (template) => {
  inputMessage.value = template.content
  showTemplates.value = false
}

// 加载会话
const loadSession = async (session) => {
  try {
    const response = await getChatHistory({ sessionId: session.id })
    if (response.code === 200) {
      messages.value = response.data
      currentSessionId.value = session.id
      showHistory.value = false
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载会话失败:', error)
    ElMessage.error('加载会话失败')
  }
}

// 删除会话
const deleteSession = async (session) => {
  try {
    await ElMessageBox.confirm(`确认要删除会话"${session.title}"吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteChatSession(session.id)
    ElMessage.success('会话已删除')
    loadChatSessions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会话失败:', error)
      ElMessage.error('删除会话失败')
    }
  }
}

// 复制消息
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 重新生成消息
const regenerateMessage = (message) => {
  // 找到这条消息的前一条用户消息，重新发送
  const messageIndex = messages.value.findIndex(m => m.id === message.id)
  if (messageIndex > 0) {
    const userMessage = messages.value[messageIndex - 1]
    if (userMessage.role === 'user') {
      // 移除AI消息
      messages.value.splice(messageIndex, 1)
      // 重新发送用户消息
      inputMessage.value = userMessage.content
      handleSend()
    }
  }
}

// 文件上传
const handleFileUpload = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await uploadChatFile(formData)
    if (response.code === 200) {
      inputMessage.value += `\n[文件: ${file.name}]`
      ElMessage.success('文件上传成功')
    }
  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')
  }
  return false // 阻止默认上传
}

// 语音输入
const toggleVoiceInput = () => {
  ElMessage.info('语音输入功能开发中...')
}

// 格式化消息
const formatMessage = (content) => {
  // 简单的markdown渲染
  return content
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\n/g, '<br>')
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleTimeString()
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 页面加载
onMounted(() => {
  loadAvailableModels()
  loadChatTemplates()
  loadChatSessions()
})
</script>

<style lang="scss" scoped>
.ai-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #eee;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .ai-info {
      h3 {
        margin: 0;
        font-size: 16px;
      }
      
      p {
        margin: 0;
        font-size: 12px;
        color: #666;
      }
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  
  .message-item {
    display: flex;
    gap: 12px;
    margin-bottom: 20px;
    
    &.user-message {
      flex-direction: row-reverse;
      
      .message-content {
        background: #007bff;
        color: white;
        border-radius: 18px 18px 4px 18px;
      }
    }
    
    &.ai-message {
      .message-content {
        background: white;
        border-radius: 18px 18px 18px 4px;
        box-shadow: 0 1px 2px rgba(0,0,0,0.1);
      }
    }
    
    .message-content {
      max-width: 70%;
      padding: 12px 16px;
      
      .message-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        font-size: 12px;
        opacity: 0.7;
      }
      
      .message-text {
        line-height: 1.5;
        word-wrap: break-word;
      }
      
      .message-actions {
        margin-top: 8px;
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .typing-indicator {
    display: flex;
    gap: 4px;
    
    span {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #ccc;
      animation: typing 1.4s infinite ease-in-out;
      
      &:nth-child(1) { animation-delay: -0.32s; }
      &:nth-child(2) { animation-delay: -0.16s; }
    }
  }
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.chat-input {
  background: white;
  border-top: 1px solid #eee;
  padding: 16px 20px;
  
  .input-tools {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
  }
  
  .input-area {
    display: flex;
    gap: 12px;
    align-items: flex-end;
    
    .el-textarea {
      flex: 1;
    }
    
    .send-button {
      height: 40px;
    }
  }
}

.template-list {
  .template-item {
    padding: 16px;
    border: 1px solid #eee;
    border-radius: 8px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.3s;
    
    &:hover {
      border-color: #007bff;
      background: #f8f9fa;
    }
    
    h4 {
      margin: 0 0 8px 0;
      font-size: 14px;
    }
    
    p {
      margin: 0;
      font-size: 12px;
      color: #666;
    }
  }
}

.history-list {
  .history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    
    &:hover {
      background: #f8f9fa;
    }
    
    .session-info {
      h4 {
        margin: 0 0 4px 0;
        font-size: 14px;
      }
      
      p {
        margin: 0;
        font-size: 12px;
        color: #666;
      }
    }
  }
}

@media (max-width: 768px) {
  .chat-header {
    padding: 12px 16px;
    
    .header-right {
      gap: 8px;
    }
  }
  
  .chat-messages {
    padding: 16px;
    
    .message-item .message-content {
      max-width: 85%;
    }
  }
  
  .chat-input {
    padding: 12px 16px;
  }
}
</style>
